package com.czkspringcloud.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 自定义线程池的配置类
 *
 * @Author:ChenZhangKun
 * @Date: 2021/10/25 14:38
 */
@Configuration
public class ThreadPoolConfig {
    @Value("${core.size}")
    private Integer coreZie;

    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {
        System.out.println("核心线程数" + coreZie);
        return new ThreadPoolExecutor(coreZie,
                10,
                5000L,
                TimeUnit.MICROSECONDS,
                new MyLinkedBlockingQueue<>(3),
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread.currentThread().setName("czk");
                        return Thread.currentThread();
                    }
                },
                new RejectedExecutionHandler() {
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        // 移除该任务
                        System.out.println("进入拒绝策略了");
                        executor.remove(r);
                    }
                });
    }
}
